package com.chif.gulimall.product.exception;

import com.chif.common.exception.BizCodeEnum;
import com.chif.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * AOP处理所有异常
 * @author liuzilong
 * @date 2022/9/23 14:33
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.chif.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    /**
     * 数据校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验异常{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        //BindingResult是@Valid 校验的结果
        HashMap<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            String defaultMessage = item.getDefaultMessage();
            String field = item.getField();
            map.put(field,defaultMessage);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }

}
